#include "Ground.h"
#include "config.h"
#include "Gold.h"

Ground::Ground(CCNode * parent, b2World * w, const CCPoint & start)
: Topography(parent, w, start)
{
}

Ground::~Ground()
{}

Ground * Ground::create(CCNode * parent, b2World * w, const CCPoint & sP)
{
  Ground * pGround = new Ground(parent, w, sP);
  if (pGround && pGround->init())
  {
    pGround->autorelease();
    return pGround;
  }
  else
  {
    CC_SAFE_DELETE(pGround);
    return NULL; 
  }
}

bool Ground::init()
{
  do
  {
    createBody();
    setPTMRatio(PTM_RATIO);
    initWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("land.png"));
    this->pParent->addChild((Topography *)this);
    this->setAnchorPoint(ccp(0, 1));

    Gold * pGold = Gold::create(this->pWorld, ccp((this->startPoint.x + this->endPoint.x)/2, this->startPoint.y + 2.5));
    this->addEntity(pGold);
    
    return true;
  } while (0);
  return false;
}

void Ground::createBody()
{
  endPoint = ccp(startPoint.x + WORLD_WIDTH, startPoint.y);
  b2BodyDef groundBodyDef;
  groundBodyDef.position.Set(startPoint.x, startPoint.y);

  m_pB2Body = pWorld->CreateBody(&groundBodyDef);

  b2EdgeShape groundBox;
  
  groundBox.Set(b2Vec2(0, 0), b2Vec2(WORLD_WIDTH, 0));
  m_pB2Body->CreateFixture(&groundBox, 0);

  m_pB2Body->SetUserData((GameEntity *)this);
}

Topography * Ground::createNext()
{
  return Ground::create(this->pParent, this->pWorld, this->endPoint);
}
